package com.ctrip.cap.monitor.common;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import com.ctrip.cap.device.android.AndroidDevice;
import com.ctrip.cap.monitor.utils.LogUtil;

public class TaskAdapter {
	protected AtomicBoolean isStart;
	protected AndroidDevice mDevice;
	protected boolean isStop;
	private Timer mTimer;
	private String mTag;

	public TaskAdapter(AndroidDevice device, AtomicBoolean isStart) {
		this.isStart = isStart;
		this.mTag = getClass().getSimpleName();
		this.mDevice = device;
		setStart(isStart.get());
	}

	public synchronized void stop() {
		if (mTimer != null) {
			mTimer.cancel();
		}
		isStop = true;
	}

	public synchronized void setStart(boolean flag) {
		isStart.set(flag);
		if (flag) {
			if (mTimer != null) {
				mTimer.cancel();
			}
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					synchronized (this) {
						isStart.set(false);
						StringBuilder sb = new StringBuilder();
						sb.append("Device connect time out ----- ");
						sb.append(mTag);
						sb.append(Constants.ENTER);
						sb.append("UDID    :\t");
						sb.append(mDevice.getSerialNumber());
						LogUtil.info(sb.toString());
					}
				}
			}, Constants.DEFAULT_TIME_OUT);
		}
	}
}
